//
//  SetLoginPasswordViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "SetLoginPasswordViewController.h"

@interface SetLoginPasswordViewController ()
@property (nonatomic, strong)UITextField * oldCodeTextField;
@property (nonatomic, strong)UITextField * freshCodeTextField;
@end

@implementation SetLoginPasswordViewController (networking)
- (void)sendVerificationCodeData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"phone_code":self.verificationCodeStr,
                           @"newPass":self.oldCodeTextField.text,
                           @"userPass":self.freshCodeTextField.text,
                           @"token":[UserModel sharedInstanced].token,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"phone_code":self.verificationCodeStr,
                               @"newPass":self.oldCodeTextField.text,
                               @"userPass":self.freshCodeTextField.text,
                               @"token":[UserModel sharedInstanced].token,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userInfo/index?api=api1004"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
//            if ([compareMD5Str isEqualToString:signResult]) {
//                NSLog(@"成功");
////                NSDictionary * contentDic = jsonData[@"body"][0];
//            }else{
//                NSLog(@"失败");
//                if ([jsonData[@"code"] isEqualToString:@"000000"]) {
//                    [self.navigationController popToRootViewControllerAnimated:YES];
//                }else{
//                    [self.view makeToast:jsonData[@"msg"] duration:1 position:CSToastPositionCenter];
//                }
//            }
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    if ([compareMD5Str isEqualToString:signResult]) {
                        NSLog(@"成功");
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }else{
                        NSLog(@"失败");
                    }
                }else{
                    NSLog(@"无内容");
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end

@implementation SetLoginPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置登录密码";
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpViews];
}

- (void)setUpViews{
    __weak typeof (self)weakSelf = self;
    //旧密码
    self.oldCodeTextField = [[UITextField alloc] init];
    self.oldCodeTextField.placeholder = @"请输入原密码";
    self.oldCodeTextField.font = DEF_FontSize_14;
    self.oldCodeTextField.layer.cornerRadius = 6;
    self.oldCodeTextField.layer.borderWidth = 1;
    self.oldCodeTextField.layer.borderColor = getColor(grayColor).CGColor;
    self.oldCodeTextField.layer.masksToBounds = YES;
    [self.view addSubview:self.oldCodeTextField];
    //新密码
    self.freshCodeTextField = [[UITextField alloc] init];
    self.freshCodeTextField.placeholder = @"请输入新密码";
    self.freshCodeTextField.font = DEF_FontSize_14;
    self.freshCodeTextField.layer.cornerRadius = 6;
    self.freshCodeTextField.layer.borderWidth = 1;
    self.freshCodeTextField.layer.borderColor = getColor(grayColor).CGColor;
    self.freshCodeTextField.layer.masksToBounds = YES;
    [self.view addSubview:self.freshCodeTextField];
    //确认
    UIButton * sureBtn = [[UIButton alloc] init];
    [self button:sureBtn withBGColor:getColor(@"3675bd") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
    [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.titleLabel.font = DEF_FontSize_12;
    //masonry
    [self.oldCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).mas_offset(18/WIDTH_6_SCALE);
        make.right.equalTo(weakSelf.view.mas_right).mas_offset(-18/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.view.mas_top).mas_offset(20/WIDTH_6_SCALE);
        make.height.mas_offset(44/WIDTH_6_SCALE);
    }];
    [self.freshCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(weakSelf.oldCodeTextField);
        make.top.equalTo(weakSelf.oldCodeTextField.mas_bottom).mas_offset(12/WIDTH_6_SCALE);
    }];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).mas_offset(57/WIDTH_6_SCALE);
        make.right.equalTo(weakSelf.view.mas_right).mas_offset(-58/WIDTH_6_SCALE);
        make.height.mas_offset(38/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.freshCodeTextField.mas_bottom).mas_offset(44/WIDTH_6_SCALE);
    }];
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sureBtnClick:(UIButton *)sender{
    if (([self.oldCodeTextField.text isEqualToString:@""] || self.oldCodeTextField.text == nil || self.oldCodeTextField.text.length == 0) && ([self.freshCodeTextField.text isEqualToString:@""] || self.freshCodeTextField.text == nil || self.freshCodeTextField.text.length == 0)) {
        [self.view makeToast:@"请正确的输入密码" duration:2 position:CSToastPositionCenter];
    }else{
        [self sendVerificationCodeData];
    }
}
@end
